package com.tust.app.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tust.app.consts.Constants;
import com.tust.app.domain.TVideo;
import com.tust.app.service.TVideoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Date;
import java.util.List;

@Controller
public class VideoController {
    @Autowired
    private TVideoService videoService;

    @RequestMapping("/getAllVideo")
    public String getAllVideo(Integer pn, HttpServletRequest request) {
        try {
            String username = (String) request.getSession().getAttribute("username");
            if (username == null){
                return "forward:/checkLogin";
            }
            if (pn == null) {
                pn = 1;
            }
            PageHelper.startPage(pn, Constants.mainPageSize);
            List<TVideo> videoList = videoService.selectAll();
            PageInfo<TVideo> page = new PageInfo<>(videoList);
            request.setAttribute("videoList", page);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("视频模块分页查询失败！");
        }
        return "frontPage/allVideo";
    }

    @RequestMapping("/getAllVideo2")
    public String getAllVideo2(Integer pn, HttpServletRequest request) {
        try {
            if (pn == null) {
                pn = 1;
            }
            PageHelper.startPage(pn, Constants.mainPageSize);
            List<TVideo> videoList = videoService.selectAll();
            PageInfo<TVideo> page = new PageInfo<>(videoList);
            request.setAttribute("videoList", page);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("按固定页码做分页查询失败！");
        }

        return "admin/movie/allVideo";
    }

    @RequestMapping("/deleteVideoById")
    public String deleteVideoById(Integer id, HttpServletRequest request) {
        try {
            TVideo video = videoService.selectByPrimaryKey(id);
            if (video != null) {
                // 删除数据库中的记录
                videoService.deleteByPrimaryKey(id);

                // 删除对应的视频文件
                String filePath = request.getServletContext().getRealPath(video.getPath()); // 获取视频文件的绝对路径
                File file = new File(filePath);
                if (file.exists()) {
                    if (file.delete()) {
                        System.out.println("视频文件删除成功");
                    } else {
                        System.out.println("视频文件删除失败");
                    }
                } else {
                    System.out.println("视频文件不存在");
                }
            }

            // 重新查询视频列表并设置到request中
            PageHelper.startPage(1, Constants.mainPageSize);
            List<TVideo> videoList = videoService.selectAll();
            PageInfo<TVideo> page = new PageInfo<>(videoList);
            request.setAttribute("videoList", page);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("按固定页码做分页查询失败！");
        }

        return "admin/movie/allVideo";
    }


    @PostMapping("/videoUpload")
    public String handleVideoUpload(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
        if (file.isEmpty()) {
            return "admin/movie/videoUploadFail"; // 返回错误页面
        }
        try {
            // 获取webapp目录下的upload文件夹路径
            String uploadPath = request.getServletContext().getRealPath("/upload/video");

            // 生成唯一的文件名
            String originalFilename = file.getOriginalFilename();

            if (!originalFilename.endsWith(".mp4")) {
                System.out.println("文件不为.mp4结尾");
                return "admin/movie/videoUploadFail"; // 返回错误页面
            }
            System.out.println("找到MP4文件");

            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf(".")); // 获取文件后缀
            String uniqueFileName = System.currentTimeMillis() + fileExtension;

            // 保存文件到指定目录
            Path targetPath = Paths.get(uploadPath, uniqueFileName);
            Files.copy(file.getInputStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);

            // 创建 TVideo 对象并保存到数据库
            TVideo video = new TVideo();
            video.setTitleOrig(originalFilename.substring(0, originalFilename.lastIndexOf("."))); // 去掉后缀的文件名
            video.setSize(formatFileSize(file.getSize())); // 格式化文件大小
            video.setType("." + file.getContentType().substring(file.getContentType().lastIndexOf("/") + 1)); // 获取文件类型后缀
            video.setPath("/upload/video/" + uniqueFileName); // 保存相对路径
            video.setUploadTime(new Date());
            video.setTitleAlter(uniqueFileName.substring(0, uniqueFileName.lastIndexOf("."))); // 生成titleAlter

            // 调用你的 Service 层方法保存 video 到数据库
            videoService.insert(video);
            // 返回成功页面
            return "admin/movie/videoUploadSuccess";
        } catch (IOException e) {
            return "admin/movie/videoUploadFail"; // 返回错误页面
        }
    }

    @GetMapping("/download")
    public void downloadFile(@RequestParam("filename") String path, HttpServletRequest request, HttpServletResponse response) {

        if (path.isEmpty()) {
            return;
        }
        try {
            // 获取webapp目录下的upload文件夹路径
//            String uploadPath = request.getServletContext().getRealPath("/upload/video");
            String uploadPath = request.getServletContext().getRealPath("/");

            // 保存文件到指定目录
            Path targetPath = Paths.get(uploadPath, path);

            if (!targetPath.toFile().isFile()) {
                System.out.println("文件不存在 in VideoController.java");
                return;
            }

            // 将文件写入输入流
            FileInputStream fileInputStream = new FileInputStream(targetPath.toFile());
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[fis.available()];
            if (fis.read(buffer) == -1) System.out.println("fis.read wrong in VideoController.java");
            fis.close();

            // 清空response
            response.reset();
            // 设置response的Header
            response.setCharacterEncoding("UTF-8");
            //Content-Disposition的作用：告知浏览器以何种方式显示响应返回的文件，用浏览器打开还是以附件的形式下载到本地保存
            //attachment表示以附件方式下载   inline表示在线打开   "Content-Disposition: inline; filename=文件名.mp3"
            // filename表示文件的默认名称，因为网络传输只支持URL编码的相关支付，因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
            response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(targetPath.toFile().getName(), "UTF-8"));
            // 告知浏览器文件的大小
            response.addHeader("Content-Length", "" + targetPath.toFile().length());
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            outputStream.write(buffer);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 格式化文件大小
    private String formatFileSize(long size) {
        long kb = 1024;
        long mb = kb * 1024;
        if (size < kb) {
            return size + "B";
        } else if (size < mb) {
            return String.format("%.2fKB", (double) size / kb);
        } else {
            return String.format("%.2fMB", (double) size / mb);
        }
    }
    
    @RequestMapping("/play")
    public String play(Integer id, HttpServletRequest request, Model model) {
        try {
            TVideo tVideo = videoService.selectByPrimaryKey(id);
            if (tVideo != null) {
                model.addAttribute("path", tVideo.getPath());
                return "frontPage/playVideo";
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("播放失败！");
        }
        return "error";
    }
}
